<!doctype html>
<html>
<head>
  <meta charset="utf-8"/>
  <title>Babylon.js Playground</title>
  <meta name="viewport" content="width=device-width,initial-scale=1"/>

  <!-- Babylon globals (kept so window.BABYLON is available if your app expects it) -->
  <script src="https://assets.babylonjs.com/generated/Assets.js"></script>
  <script src="https://cdn.babylonjs.com/recast.js"></script>
  <script src="https://cdn.babylonjs.com/ammo.js"></script>
  <script src="https://cdn.babylonjs.com/havok/HavokPhysics_umd.js"></script>
  <script src="https://cdn.babylonjs.com/cannon.js"></script>
  <script src="https://cdn.babylonjs.com/Oimo.js"></script>
  <script src="https://cdn.babylonjs.com/earcut.min.js"></script>
  <script src="https://cdn.babylonjs.com/babylon.js"></script>
  <script src="https://cdn.babylonjs.com/materialsLibrary/babylonjs.materials.min.js"></script>
  <script src="https://cdn.babylonjs.com/proceduralTexturesLibrary/babylonjs.proceduralTextures.min.js"></script>
  <script src="https://cdn.babylonjs.com/postProcessesLibrary/babylonjs.postProcess.min.js"></script>
  <script src="https://cdn.babylonjs.com/loaders/babylonjs.loaders.js"></script>
  <script src="https://cdn.babylonjs.com/serializers/babylonjs.serializers.min.js"></script>
  <script src="https://cdn.babylonjs.com/gui/babylon.gui.min.js"></script>
  <script src="https://cdn.babylonjs.com/addons/babylonjs.addons.min.js"></script>
  <script src="https://cdn.babylonjs.com/inspector/babylon.inspector.bundle.js"></script>

  <style>
    html,body,#renderCanvas{width:100%;height:100%;margin:0;padding:0;overflow:hidden;background:#000}
  </style>
</head>
<body>
  <canvas id="renderCanvas"></canvas>
  <script>
    const BABYLON = window.BABYLON;
    const canvas = document.getElementById('renderCanvas');

    // 创建场景函数
    function createScene(engine) {
      const scene = new BABYLON.Scene(engine);
      scene.clearColor = new BABYLON.Color4(0.01, 0.01, 0.05, 1);  // 深邃的太空黑色
      
      // 创建相机 - 环绕相机更适合观察3D模型
      const camera = new BABYLON.ArcRotateCamera("camera", 
        -Math.PI / 2, Math.PI / 2.5, 8, 
        new BABYLON.Vector3(0, 0, 0), scene);
      camera.attachControl(canvas, true);
      camera.lowerRadiusLimit = 4;
      camera.upperRadiusLimit = 15;
      
      // 创建光源
      const light1 = new BABYLON.HemisphericLight("light1", new BABYLON.Vector3(1, 1, 0), scene);
      light1.intensity = 0.8;
      const light2 = new BABYLON.PointLight("light2", new BABYLON.Vector3(0, 3, -3), scene);
      light2.intensity = 0.6;
      const light3 = new BABYLON.PointLight("light3", new BABYLON.Vector3(-3, 2, 2), scene);
      light3.intensity = 0.4;
      
      // ===== 创建宇宙星空背景 =====
      // 创建大型球体作为星空背景
      const starfieldSphere = BABYLON.MeshBuilder.CreateSphere("starfield", {
        diameter: 200,
        segments: 32
      }, scene);
      
      // 星空材质
      const starfieldMaterial = new BABYLON.StandardMaterial("starfieldMat", scene);
      starfieldMaterial.emissiveColor = new BABYLON.Color3(0.05, 0.05, 0.1);
      starfieldMaterial.backFaceCulling = false;  // 从内部也能看到
      
      // 使用程序纹理创建星空
      const starTexture = new BABYLON.DynamicTexture("starTexture", 1024, scene);
      const context = starTexture.getContext();
      const size = 1024;
      
      // 绘制深色太空背景
      context.fillStyle = "#000008";
      context.fillRect(0, 0, size, size);
      
      // 绘制随机星星
      for (let i = 0; i < 800; i++) {
        const x = Math.random() * size;
        const y = Math.random() * size;
        const radius = Math.random() * 1.5;
        const brightness = Math.random() * 255;
        const starColor = brightness > 200 ? 
          `rgb(${brightness}, ${brightness}, 255)` :  // 蓝白色亮星
          `rgb(${brightness}, ${brightness}, ${brightness})`; // 普通星星
        
        context.beginPath();
        context.arc(x, y, radius, 0, Math.PI * 2);
        context.fillStyle = starColor;
        context.fill();
        
        // 随机添加星光效果
        if (Math.random() > 0.9) {
          context.strokeStyle = `rgba(${brightness}, ${brightness}, 255, 0.3)`;
          context.lineWidth = 1;
          context.beginPath();
          context.moveTo(x - radius * 3, y);
          context.lineTo(x + radius * 3, y);
          context.moveTo(x, y - radius * 3);
          context.lineTo(x, y + radius * 3);
          context.stroke();
        }
      }
      
      starTexture.update();
      starfieldMaterial.emissiveTexture = starTexture;
      starfieldSphere.material = starfieldMaterial;
      
      // 添加远景星尘粒子效果
      const particleSystem = new BABYLON.ParticleSystem("particles", 2000, scene);
      
      // 粒子发射器（整个空间）
      particleSystem.emitter = new BABYLON.Vector3(0, 0, 0);
      particleSystem.minEmitBox = new BABYLON.Vector3(-50, -50, -50);
      particleSystem.maxEmitBox = new BABYLON.Vector3(50, 50, 50);
      
      // 粒子外观
      particleSystem.particleTexture = new BABYLON.Texture("https://assets.babylonjs.com/textures/flare.png", scene);
      particleSystem.color1 = new BABYLON.Color4(0.7, 0.8, 1.0, 0.8);
      particleSystem.color2 = new BABYLON.Color4(0.9, 0.9, 1.0, 0.6);
      particleSystem.colorDead = new BABYLON.Color4(0, 0, 0.2, 0.0);
      
      // 粒子大小
      particleSystem.minSize = 0.1;
      particleSystem.maxSize = 0.5;
      
      // 粒子生命周期
      particleSystem.minLifeTime = 999;
      particleSystem.maxLifeTime = 999;
      
      // 发射速率
      particleSystem.emitRate = 2000;
      
      // 粒子速度（几乎静止，像远处的星星）
      particleSystem.minEmitPower = 0;
      particleSystem.maxEmitPower = 0;
      particleSystem.updateSpeed = 0.001;
      
      // 混合模式
      particleSystem.blendMode = BABYLON.ParticleSystem.BLENDMODE_ADD;
      
      particleSystem.start();
      
      // 环境光源用于反射
      const hdrTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(
        "https://assets.babylonjs.com/environments/environmentSpecular.env", 
        scene
      );
      scene.environmentTexture = hdrTexture;
      scene.environmentIntensity = 0.4;  // 降低环境光强度，营造太空感
      
      // ===== 创建球形储箱 (透明外壳) =====
      const tank = BABYLON.MeshBuilder.CreateSphere("tank", {
        diameter: 4,
        segments: 64  // 增加分段数，表面更平滑
      }, scene);
      
      // 储箱材质 - 半透明金属效果（使用PBR材质）
      const tankMaterial = new BABYLON.PBRMaterial("tankMat", scene);
      tankMaterial.metallic = 0.95;             // 高金属度
      tankMaterial.roughness = 0.25;            // 磨砂金属表面
      tankMaterial.alpha = 0.35;                // 半透明度（可以看到内部）
      
      // 金属色调 - 银灰色/钛合金色
      tankMaterial.albedoColor = new BABYLON.Color3(0.7, 0.75, 0.78);
      tankMaterial.reflectivityColor = new BABYLON.Color3(0.85, 0.85, 0.88);
      tankMaterial.microSurface = 0.75;         // 金属表面微观粗糙度
      tankMaterial.environmentIntensity = 1.5;  // 强烈的环境反射（金属特性）
      
      // 启用透明度
      tankMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_ALPHABLEND;
      
      tank.material = tankMaterial;
      
      // ===== 创建推进剂 (内部液体) =====
      const propellant = BABYLON.MeshBuilder.CreateSphere("propellant", {
        diameter: 3.9,  // 略小于储箱
        segments: 64    // 增加分段数，表面更光滑
      }, scene);
      
      // 推进剂材质 - 半透明黄色液体（使用PBR材质）
      const propellantMaterial = new BABYLON.PBRMaterial("propellantMat", scene);
      propellantMaterial.metallic = 0.0;              // 非金属
      propellantMaterial.roughness = 0.15;            // 较光滑，有液体光泽
      propellantMaterial.alpha = 0.7;                 // 半透明效果
      propellantMaterial.indexOfRefraction = 1.33;    // 液体折射率（类似水）
      
      // 黄色液体颜色
      propellantMaterial.albedoColor = new BABYLON.Color3(1.0, 0.85, 0.1);
      propellantMaterial.emissiveColor = new BABYLON.Color3(0.25, 0.18, 0.0);  // 发光效果
      propellantMaterial.emissiveIntensity = 0.5;
      
      // 液体效果设置
      propellantMaterial.reflectivityColor = new BABYLON.Color3(0.6, 0.5, 0.2);
      propellantMaterial.microSurface = 0.85;         // 液体表面光滑度
      propellantMaterial.environmentIntensity = 0.8;
      
      // 启用透明度和折射（液体效果）
      propellantMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_ALPHABLEND;
      propellantMaterial.subSurface.isRefractionEnabled = true;
      propellantMaterial.subSurface.refractionIntensity = 0.6;
      propellantMaterial.subSurface.tintColor = new BABYLON.Color3(1.0, 0.9, 0.3);  // 液体内部颜色
      propellantMaterial.subSurface.tintColorAtDistance = 2.0;
      
      propellant.material = propellantMaterial;
      
      // ===== 使用裁剪平面实现液体减少效果 =====
      // 创建裁剪平面（从下往上裁剪，模拟液体减少）
      const clipPlane = new BABYLON.Plane(0, 1, 0, 2);  // 法向量(0,1,0)向上，距离为2
      propellantMaterial.clipPlane = clipPlane;
      
      // 动画参数
      let currentHeight = 2.0;  // 液面初始高度（球体半径为2）
      const minHeight = -2.0;   // 最低高度
      const drainSpeed = 0.3;   // 排放速度 (单位/秒)
      
      // 添加UI信息
      const advancedTexture = BABYLON.GUI.AdvancedDynamicTexture.CreateFullscreenUI("UI");
      
      const panel = new BABYLON.GUI.StackPanel();
      panel.width = "300px";
      panel.horizontalAlignment = BABYLON.GUI.Control.HORIZONTAL_ALIGNMENT_RIGHT;
      panel.verticalAlignment = BABYLON.GUI.Control.VERTICAL_ALIGNMENT_TOP;
      panel.top = "20px";
      panel.left = "-20px";
      advancedTexture.addControl(panel);
      
      const infoText = new BABYLON.GUI.TextBlock();
      infoText.text = "推进剂储箱演示";
      infoText.height = "30px";
      infoText.color = "white";
      infoText.fontSize = 20;
      infoText.textHorizontalAlignment = BABYLON.GUI.Control.HORIZONTAL_ALIGNMENT_LEFT;
      panel.addControl(infoText);
      
      const levelText = new BABYLON.GUI.TextBlock();
      levelText.height = "30px";
      levelText.color = "#FFD700";
      levelText.fontSize = 16;
      levelText.textHorizontalAlignment = BABYLON.GUI.Control.HORIZONTAL_ALIGNMENT_LEFT;
      panel.addControl(levelText);
      
      const buttonPanel = new BABYLON.GUI.StackPanel();
      buttonPanel.height = "120px";
      buttonPanel.isVertical = true;
      panel.addControl(buttonPanel);
      
      // 重新加满按钮
      const refillButton = BABYLON.GUI.Button.CreateSimpleButton("refill", "重新加满");
      refillButton.width = "150px";
      refillButton.height = "35px";
      refillButton.color = "white";
      refillButton.background = "#2196F3";
      refillButton.cornerRadius = 5;
      refillButton.paddingTop = "5px";
      refillButton.onPointerClickObservable.add(() => {
        currentHeight = 2.0;
      });
      buttonPanel.addControl(refillButton);
      
      // 加速排放按钮
      const speedButton = BABYLON.GUI.Button.CreateSimpleButton("speed", "加速排放");
      speedButton.width = "150px";
      speedButton.height = "35px";
      speedButton.color = "white";
      speedButton.background = "#FF9800";
      speedButton.cornerRadius = 5;
      speedButton.paddingTop = "5px";
      let isSpeedUp = false;
      speedButton.onPointerClickObservable.add(() => {
        isSpeedUp = !isSpeedUp;
        speedButton.textBlock.text = isSpeedUp ? "正常速度" : "加速排放";
        speedButton.background = isSpeedUp ? "#4CAF50" : "#FF9800";
      });
      buttonPanel.addControl(speedButton);
      
      // 动画循环
      scene.onBeforeRenderObservable.add(() => {
        // 更新液面高度
        if (currentHeight > minHeight) {
          const speed = isSpeedUp ? drainSpeed * 3 : drainSpeed;
          currentHeight -= speed * engine.getDeltaTime() / 1000;
          if (currentHeight < minHeight) currentHeight = minHeight;
        }
        
        // 更新裁剪平面位置
        clipPlane.d = currentHeight;
        
        // 计算百分比 (0-100%)
        let percentage = ((currentHeight - minHeight) / (2.0 - minHeight)) * 100;
        percentage = Math.max(0, Math.min(100, percentage));
        
        // 更新UI显示
        levelText.text = "液位: " + percentage.toFixed(1) + "%";
        
        // 当液体快用完时，改变颜色提示
        if (percentage < 20) {
          levelText.color = "#FF4444";
          propellantMaterial.emissiveColor = new BABYLON.Color3(0.35, 0.05, 0.0);
          propellantMaterial.emissiveIntensity = 0.8;  // 增强警告效果
        } else {
          levelText.color = "#FFD700";
          propellantMaterial.emissiveColor = new BABYLON.Color3(0.25, 0.18, 0.0);
          propellantMaterial.emissiveIntensity = 0.5;  // 正常发光
        }
      });
      
      // 添加说明文本
      const instructionText = new BABYLON.GUI.TextBlock();
      instructionText.text = "鼠标拖动旋转视角\n滚轮缩放";
      instructionText.height = "50px";
      instructionText.color = "rgba(255,255,255,0.6)";
      instructionText.fontSize = 14;
      instructionText.textVerticalAlignment = BABYLON.GUI.Control.VERTICAL_ALIGNMENT_BOTTOM;
      instructionText.top = "-20px";
      advancedTexture.addControl(instructionText);
      
      return scene;
    }

    // 初始化引擎和场景
    const engine = new BABYLON.Engine(canvas, true, { 
      preserveDrawingBuffer: true, 
      stencil: true 
    });
    
    const scene = createScene(engine);
    
    // 渲染循环
    engine.runRenderLoop(() => {
      scene.render();
    });
    
    // 窗口大小调整
    window.addEventListener('resize', () => {
      engine.resize();
    });
  </script>
</body>
</html>